<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="入库单号" value="inbound_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="异常单号" value="abnormal_no"></el-option>
            <el-option label="外验编号" value="inspection_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.skuInfo.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.abnormal_method" placeholder="异常类型" :options="options.abnormal_method" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.abnormal_type" placeholder="不良类型" :options="options.abnormal_type" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple
          collapse-tags clearable filterable />
        <VSelect v-model="form.warehouse" placeholder="仓库" type="warehouse156" multiple collapse-tags filterable
          clearable style="min-width: 160px" />
        <VSelect v-model="form.is_external_inspection" placeholder="是否外验" :options="options.is_external_inspection"
          multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.is_complete_replenishment" placeholder="是否完善补货信息"
          :options="options.is_complete_replenishment" multiple collapse-tags filterable clearable
          style="min-width: 166px" />
        <VSelect v-model="form.abnormal_status" placeholder="异常单状态" :options="options.abnormal_status" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VCascader v-model="form.process_user_id" placeholder="处理人" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="质检时间" value="qa_time"></el-option>
            <el-option label="采购处理时间" value="process_time"></el-option>
            <el-option label="仓库处理时间" value="warehouse_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VExport auth="/purchase/manage/abnormal/export" :name="baseName" mainKey="a_id" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Add ref="addRef" />
    <VLog ref="logRef" />
    <Plan ref="planRef" @success="query" />
    <Types ref="typesRef" :options="options" @success="query" />
    <Replenishment ref="replenishmentRef" :options="options" @success="query" />
    <VAudit ref="auditRef" field="a_id" onlyone url="/v1/abnormal/abnormal/audit" @success="query" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from './api'
import Add from '@/views/manage/purchase/components/Add'
import Plan from './components/Plan'
import Types from './components/Types'
import Replenishment from './components/Replenishment'
import { getOption, supplier } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const baseName = 'abnormal'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
const processTypeOptions = ref({})
Promise.all([
  getOption({ type: 'purchase' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  getOption({ type: 'refund' }).then(res => res.data),
  getOption({ type: 'return_goods' }).then(res => res.data),
  api.logistics().then(res => ({ logisticsOptions: res.data })),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
  const { process_type } = options.value
  processTypeOptions.value = {
    '1-1': [1, 2].map(d => process_type.find(t => t.value === d)),
    '1-2': [3, 2].map(d => process_type.find(t => t.value === d)),
    '2-1': [2, 4, 5, 6, 7, 8].map(d => process_type.find(t => t.value === d)),
    '2-2': [2, 4, 5, 9, 10, 8, 11].map(d => process_type.find(t => t.value === d)),
    '3-1': [12, 13, 14].map(d => process_type.find(t => t.value === d)),
    '3-2': [12, 13, 14].map(d => process_type.find(t => t.value === d)),
  }
})

// 单行操作
const addRef = ref()
const planRef = ref()
const auditRef = ref()
const replenishmentRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { a_id, p_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      addRef?.value.open(p_id)
    },
    audit: () => {
      auditRef?.value.open([row], { label: '审核', value: 1 })
    },
    plan: () => {
      planRef?.value.open(row)
    },
    replenishment: () => {
      replenishmentRef?.value.open(row)
    },
    toPath: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { input: { type: 'return_no', value: row.doc.return_no } } }))
      router.push('/manage/return')
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, a_id })
    },
  }
  handle[name]()
}

// 处理方式
const typesRef = ref()
const handleCommand = (name, row, rowIndex) => {
  const { a_id, process_type } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  if (name === 1) {
    ElMessageBox.confirm('是否要确认该sku以当前入库数量完结，不再补货？', '备注', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(({ value }) => {
        showLoading()
        api.process({ a_id, process_type: 1 }).then(res => {
          ElMessage.success('操作成功')
          query()
        }).finally(closeLoading)
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
    return
  }
  typesRef?.value.open(row, name)
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 136 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'abnormal_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'qa_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      width: 220, slots: {
        header: () => <div>采购信息</div>,
        default: ({ row }) => <div>
          <el-link type='primary' onClick={() => handleRow('look', row)}>{row.purchase_no}</el-link>
          <VText title='供应商' value={row.supplier_name}></VText>
          <VText title='供应商id' value={row.supplier_code} />
          <VText title='结算方式' value={row.period_name} />
          <VText title='付款状态'>{row.finance_status_name}</VText>
          <VText title='采购员'>{row.purchase_user}</VText>
        </div>
      }
    },
    {
      width: 160, slots: {
        header: () => <div>入库单号<br />是否外验</div>,
        default: ({ row }) => <div>
        <VText value={row.inbound_no} />
        {row.is_external_inspection_name}
        {row.is_external_inspection === 2 ? <VText title='外验编号' value={row.inspection_no} title-position='top' /> : ''}
        </div>
      }
    },
    {
      width: 150, slots: {
        header: () => <div>异常单号<br />异常单状态</div>,
        default: ({ row }) => <div>{row.abnormal_no}<br />{row.abnormal_status_name}</div>
      }
    },
    {
      width: 90, slots: {
        header: () => <div>异常类型</div>,
        default: ({ row }) => row.abnormal_method_name
      }
    },
    {
      width: 90, slots: {
        header: () => <div>不良类型</div>,
        default: ({ row }) => row.abnormal_type_name
      }
    },
    {
      width: 120, slots: {
        header: () => <div>不良原因</div>,
        default: ({ row }) => <VText value={row.abnormal_reason_name.join(',')} line={4} />
      }
    },
    {
      width: 100, slots: {
        header: () => <div>sku</div>,
        default: ({ row }) => <VText value={row.sku} />
      }
    },
    {
      title: '图片', width: 100, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="80px"></VImage>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>仓库</div>,
        default: ({ row }) => <VText value={row.warehouse_name} />
      }
    },
    {
      width: 80, slots: {
        header: () => <div>下单数量</div>,
        default: ({ row }) => row.purchase_num
      }
    },
    {
      width: 80, slots: {
        header: () => <div>收货数量</div>,
        default: ({ row }) => row.deliver_num
      }
    },
    {
      width: 80, slots: {
        header: () => <div>质检数量</div>,
        default: ({ row }) => row.qa_num
      }
    },
    {
      width: 80, slots: {
        header: () => <div>良品数量</div>,
        default: ({ row }) => row.quality_num
      }
    },
    {
      width: 80, slots: {
        header: () => <div>上架数量</div>,
        default: ({ row }) => row.inbound_num
      }
    },
    {
      width: 80, slots: {
        header: () => <div>不良数量</div>,
        default: ({ row }) => row.reject_num
      }
    },
    {
      width: 260, slots: {
        header: () => <div>人员时间信息</div>,
        default: ({ row }) => <div>
          <VText title='质检人' value={row.qa_actually_user}></VText>
          <VText title='质检时间' value={row.qa_time}></VText>
          <VText title='采购员' value={row.purchase_user}></VText>
          <VText title='采购处理时间' value={row.process_time}></VText>
          <VText title='仓库处理人' value={row.warehouse_user}></VText>
          <VText title='仓库处理时间' value={row.warehouse_time}></VText>
        </div>
      }
    },
    {
      width: 120, slots: {
        header: () => <div>异常备注</div>,
        default: ({ row }) => <VText value={row.qa_remark} line={3} />
      }
    },
    {
      width: 100, slots: {
        header: () => <div>质检图片</div>,
        default: ({ row }) => <div class='p-2'>
          <el-badge value={row.img.length} hidden={!row.img.length}><VImage src={row.img[0]} size='70px' preview-src-list={row.img} /></el-badge>
        </div>
      }
    },
    {
      width: 220, slots: {
        header: () => <div>处理方式</div>,
        default: ({ row }) => {
          const { process_type, process_type_name } = row
          const doc = row.doc || {}
          const types = {
            1: <div>{doc.content}</div>,
            2: <div>
              <VText title='运单号'><el-link type='primary'>{doc.logistics_number}</el-link></VText>
              <VText title='预计到货时间'>{doc.except_deliver_time}</VText>
            </div>,
            3: <div>
              <VText title='退款单号' value={doc.refund_no}></VText>
              <VText title='退款单状态'>{doc.doc_status_name}</VText>
            </div>,
            4: <div>
              <VText title='采购单'><el-link type='primary'>{doc.purchase_no}</el-link></VText>
              <VText title='采购单状态'>{doc.doc_status_name}</VText>
            </div>,
            5: <div>
              <VText title='退货单号' value={doc.return_no} type='link' onClick={() => handleRow('toPath', row)}></VText>
              <VText title='退货状态'>{doc.doc_status_name}</VText>
              <VText title='补货运单号' value={doc.logistics_number} type='link'></VText>
              <VText title='补货数量'>{doc.process_num}</VText>
              <VText title='补货预计到货时间'>{doc.except_deliver_time}</VText>
            </div>,
            6: '',
            7: <div>
              <VText title='退货单号' value={doc.return_no} type='link'></VText>
              <VText title='退货状态'>{doc.doc_status_name}</VText>
            </div>,
            8: <div>
              <VText title='补货运单号' value={doc.replenishment?.logistics_number} type='link'>\</VText>
              <VText title='预计到货时间'>{doc.replenishment?.except_deliver_time}</VText>
            </div>,
            9: <div>
              <VText title='退款单号' value={doc.refund_no} type='link'></VText>
              <VText title='退款状态'>{doc.doc_status_name}</VText>
            </div>,
            10: <div>
              <VText title='退货单号' value={doc.return_no} type='link'></VText>
              <VText title='退货状态'>{doc.doc_status_name}</VText>
              <VText title='退款单号' value={doc.refund_no} type='link'></VText>
              <VText title='退款状态'>{doc.refund_doc_status_name}</VText>
            </div>,
            11: <div>
              <VText title='报损单号' value={doc.damage_no} type='link'><el-link type='primary'>{doc.damage_no}</el-link></VText>
            </div>,
            12: <div>
              <VText title='外验编号' value={doc.inspection_no} type='link'><el-link type='primary'>{doc.inspection_no}</el-link></VText>
            </div>,
            13: <div>{doc.content}</div>,
            14: <div>{doc.content}</div>,
          }
          return <div>
            <VText title='处理方式'>{process_type_name}</VText>
            {types[process_type]}
          </div>
        }
      }
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { abnormal_status, abnormal_type, payment_status, process_type } = row

          // abnormal_status	异常单状态 1待采购处理 2待计划确认 3待审核 4待仓库处理 5仓库处理完成 6已驳回 7待关联单据审核
          // abnormal_type 不良类型 1少货 2产品不良 3外验 
          // payment_status 付款状态1未付款2已付或者部分付
          const processType = processTypeOptions.value[`${abnormal_type}-${payment_status}`] || []
          // const processType = options.value?.process_type || []
          return <div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            {[2, 3, 4, 5, 7].includes(abnormal_status) && [2, 5, 8].includes(process_type) && row.is_complete_replenishment!==2 ? <VButton auth="/purchase/manage/abnormal/replenishment" link type="primary" onClick={() => handleRow('replenishment', row)}>完善补货信息</VButton> : ''}
            {[1, 6].includes(abnormal_status) ?
              <VAuth auth='/purchase/manage/abnormal/type'>
                <el-dropdown trigger="click" placement="bottom-start" onCommand={name => handleCommand(name, row, rowIndex)}>
                  {{
                    default: () => <el-button link type='primary'>处理方式<i class="dk-iconfont icon-ArrowDown" /></el-button>,
                    dropdown: () => <el-dropdown-menu v-matomo>{processType.map(d => <el-dropdown-item command={d.value}>{d.label}</el-dropdown-item>)}</el-dropdown-menu>
                  }}
                </el-dropdown></VAuth> : ''}
            {[2].includes(abnormal_status) ? <VButton auth="/purchase/manage/abnormal/planConfirm" link type="primary" onClick={() => handleRow('plan', row)}>计划确认</VButton> : ''}
            {[3].includes(abnormal_status) ? <VButton auth="/purchase/manage/abnormal/audit" link type="primary" onClick={() => handleRow('audit', row)}>审核</VButton> : ''}
            <VButton auth="/purchase/manage/abnormal/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>